package com.lzh.main.controller;

import com.lzh.main.pojo.dto.Result;
import com.lzh.main.service.FriendRelationService;
import com.lzh.main.utils.UserDetailsImpl;
import jakarta.websocket.server.PathParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/friend-relation/")
public class FriendRelationController {
    @Autowired
    private FriendRelationService friendRelationService;

    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetailsImpl) {
            return ((UserDetailsImpl) principal).getUser().getId();
        }
        throw new RuntimeException("无法获取用户ID");
    }

    @PostMapping("sendRequest/")
    public Result sendRequest(@RequestBody Map<String, String> data) {
        Integer friendId = Integer.parseInt(data.get("friendId"));
        return friendRelationService.sendRequest(getCurrentUserId(), friendId);
    }

    @PostMapping("acceptRequest/")
    public Result acceptRequest(@RequestBody Map<String, String> params) {
        Integer friendId = Integer.parseInt(params.get("friendId"));
        return friendRelationService.acceptRequest(getCurrentUserId(), friendId);
    }

    @PostMapping("declineRequest/")
    public Result declineRequest(@RequestBody Map<String, String> params) {
        Integer friendId = Integer.parseInt(params.get("friendId"));
        return friendRelationService.declineRequest(getCurrentUserId(), friendId);
    }

    @DeleteMapping("deleteFriend/")
    public Result deleteFriend(@RequestParam Integer friendId) {
        return friendRelationService.deleteFriend(getCurrentUserId(), friendId);
    }

    @GetMapping("getFriendList/")
    public Result getFriendList() {
        return friendRelationService.getFriendList(getCurrentUserId());
    }

    @GetMapping("getFriendRequests/")
    public Result getFriendRequests() {
        return friendRelationService.getFriendRequests(getCurrentUserId());
    }

    @GetMapping("getFriendInfo/")
    public Result getFriendInfo(@RequestParam Integer friendId) {
        return friendRelationService.getFriendInfo(getCurrentUserId(),friendId);
    }
}
